class RecommendationSystem {
    constructor() {
        this.userPreferences = this.loadUserPreferences();
        this.viewHistory = this.loadViewHistory();
        this.startId = 100; // 从100开始避免与主要产品ID冲突
    }

    loadUserPreferences() {
        // 从localStorage加载用户偏好
        return JSON.parse(localStorage.getItem('userPreferences')) || {};
    }

    loadViewHistory() {
        // 从localStorage加载浏览历史
        return JSON.parse(localStorage.getItem('viewHistory')) || [];
    }

    getRecommendations() {
        // 基于用户偏好和浏览历史生成推荐
        const recommendations = this.calculateRecommendations();
        this.displayRecommendations(recommendations);
    }

    calculateRecommendations() {
        // 实现推荐算法
        return [
            {
                id: this.startId + 1,
                image: 'images/轮播图2.jpg',
                name: '健康套餐A',
                price: 22,
                description: '适合健身人士的低脂套餐',
                soldCount: 189
            },
            // 添加更多推荐...
        ];
    }

    displayRecommendations(recommendations) {
        const recommendationsGrid = document.querySelector('.recommendations-grid');
        recommendationsGrid.innerHTML = '';

        // 将推荐商品添加到全局products数组
        recommendations.forEach(item => {
            if (!products.find(p => p.id === item.id)) {
                products.push(item);
            }
        });

        recommendations.forEach(item => {
            const card = document.createElement('div');
            card.className = 'product-card';
            card.innerHTML = `
                <img src="${item.image}" alt="${item.name}">
                <div class="content">
                    <h3>${item.name}</h3>
                    <p class="description">${item.description}</p>
                    <div class="price-row">
                        <span class="price">¥${item.price.toFixed(2)}</span>
                        <span class="sold">月售 ${item.soldCount || 0}</span>
                    </div>
                    <button class="add-to-cart-btn">
                        <i class="fas fa-plus"></i> 加入购物车
                    </button>
                </div>
            `;
            
            // 添加事件监听器
            const addButton = card.querySelector('.add-to-cart-btn');
            addButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                addToCart(item.id, e);
            });
            
            recommendationsGrid.appendChild(card);
        });
    }
}

// 初始化推荐系统
const recommendationSystem = new RecommendationSystem();
document.addEventListener('DOMContentLoaded', () => {
    recommendationSystem.getRecommendations();
}); 